import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { config} from '../../../shared/smartadmin.config';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
declare var $: any;
@Component({
  selector: 'sa-rail-detail',
  templateUrl: './rail-detail.component.html',
})
export class RailDetailComponent implements OnInit {
	tableData:any = []; //table数据
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	searchKey:string = ''; //搜索keyword
	deviceId:string = '';//设备ID
	selectedCarNumber:string='';
	selectedCompanyId:string = '';
	selectedCompanyName:string = '';
	companyId:string = '';
	startTime:string = '';//开始时间
	endTime:string = '';//结束时间
	railName:string='';//围栏名称
	importType:string='1';//进出站类型
	siteType:string='1';//站点类别
	filterTime:string='';//时间停留过滤
	carNumber:string = '';	//车牌号
	constructor(private jsonApiService: JsonApiService,private router: Router,) {}
	//刷新
	refresh(){
		this.load();
	}
	ngOnInit() {
		var detailCar=localStorage.getItem('detailCar');
		if(detailCar){
			this.selectedCarNumber=detailCar;
			localStorage.removeItem('detailCar');
		}
		this.initDate().then(()=>this.load());//初始化日期,加载table表格数据		
	}
	ngOnDestroy(){
		
	}
	//初始化日期
	initDate(){
		var that = this;
		return new Promise(function (resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(()=>{
					System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
						$("#datetimepicker1").datetimepicker({//时间插件
							format: "yyyy-mm-dd",
						    language: "zh-CN",
						    autoclose: true,
						    minView : 2
						}).on("changeDate", function(e){
							var date = e.date;
							if(!date){return;}
							var time = common.getTimeDay(date);
							that.startTime=time;
							$("#datetimepicker2").datetimepicker("setStartDate", time);
						});
						$("#datetimepicker2").datetimepicker({//时间插件
							format: "yyyy-mm-dd",
						    language: "zh-CN",
						    autoclose: true,
						    minView : 2
						}).on("changeDate", function(e){
							var date = e.date;
							if(!date){return;}
							var time = common.getTimeDay(date);
							that.endTime=time;
							$("#datetimepicker1").datetimepicker("setEndDate", time);
						});
						resolve();
					});
				}
			);
		})
	}	
	//擦除车牌号码所选值
	del_carNumber(){
		this.deviceId = '';
		this.selectedCarNumber='';
		if(this.selectedCompanyId){
			this.queryCarListByCompanyId(this.selectedCompanyId)
		}else{
			//采用简单粗暴的方法清除;官方推荐的方法失效
			var str=$("<span class='select2-selection__placeholder'>请选择</span>");
			$('#carNumberSelect2').val("");
			$("#select2-carNumberSelect2-container").empty();
			$("#select2-carNumberSelect2-container").attr("title","");
			$("#select2-carNumberSelect2-container").prepend(str);
		}	
	}
	//初始化select2 车辆选项
	selectCompany(){
			var that = this;
	        $("#carNumberSelect2").select2({
		    	language : "zh-CN",
		    	placeholder :"请选择",
		    	minimumInputLength : 2,      //最少2个字符，select2才显示查询的内容
		    	ajax: {
		    		url: config.BaseURL+"stats/carListByCarNumber.html",
		    		dataType: 'json',
		    		delay: 50,
		    		method: "POST",
		    		xhrFields: {
			           withCredentials: true
			      	},
		    		data: function (params) {
		    		    return {
		    		   	 "carNumber" :  params.term // search term
		    		    };
		    		},
		    		processResults: function(data, params) {
						var options = new Array();
						// 小于10个数量才判断重复
						if(data.data.length<=10){
							let arr = []
							let sameCar = []
							// 判断相同的车牌号
							for (let index = 0; index < data.data.length; index++) {
								let car = data.data[index];
								if(arr.indexOf(car.carNumber)!=-1){
									sameCar.push(car.carNumber)
								}else{
									arr.push(car.carNumber);
								}
							}
							$(data.data).each(function(index, car) {
								if(sameCar.indexOf(car.carNumber)!=-1){
									options.push({
										id: car.deviceId,
										text: car.carNumber+"["+car.parentName+"]"
									})
								}else{
									options.push({
										id: car.deviceId,
										text: car.carNumber
									})
								}
							});
						}else{
							$(data.data).each(function(index, car) {
								options.push({
									id: car.deviceId,
									text: car.carNumber
								})
							});
						}
						return {
							results: options //获取查询后的结果
						};
					},
		    		cache: true
		         },
		         templateResult: this.formatRepo
		    }).on ("select2:select", function (e) {
				  var data = e.params.data;
				  that.deviceId = data.id;
				  if(data.text.indexOf('[') > 0){
					  that.selectedCarNumber = data.text.split('[')[0];
				  } else {
					  that.selectedCarNumber = data.text;
				  }
	       });
	}
	//select2 格式回调函数
	formatRepo (state) {
		if (!state.id) {
			return state.text;
		}
		var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	//清除select2 数据
	clearSelect2(obj) {
		obj.empty();
		obj.prepend("<option value=''>请选择</option>");
	}
	//公司id拉取车辆
	queryCarListByCompanyId(companyId){
		let reqdata = 'companyId='+companyId;
		this.jsonApiService.http("stats/carlist.html", reqdata).subscribe(data => {
			var carlist = data.data;
        	var selectdata = [];
        	for(var i = 0 ; i < carlist.length ; i++) {
        		var obj = {
        			id:carlist[i].deviceId,
        			text:carlist[i].carNumber,
        		}
        		selectdata[i] = obj;
        	}
        	var selectObj = $("#carNumberSelect2");
        	this.clearSelect2(selectObj);//清除Select中的数据
        	selectObj.select2({
        		language : "zh-CN",
            	data : selectdata,//为Select添加数据
                templateResult : this.formatRepo
           });
		})
	}
	//查询
	table_search(){
		this.curPage=1;
		this.searchKey = common.stringTrim(this.searchKey);
		this.load();
	}

	//加载list数据
	load() {
		this.startTime =  $('#datetimepicker1').val();
		this.endTime =  $('#datetimepicker2').val();
		let timeCheck=common.correctTimeParams(this.startTime,this.endTime,0);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		var postData={
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				companyId:this.selectedCompanyId,//公司id
				carNumber:this.carNumber,
				startTime:this.startTime,//开始时间
				endTime:this.endTime,//结束时间
				name:common.stringTrim(this.railName),//围栏名称
				importType:this.importType,//进出站类型
				typeId:this.siteType,//站点类别
				stopTime:common.stringTrim(this.filterTime),//时间停留过滤
			}
			
		}
		let reqdata='gridPager='+JSON.stringify(postData);
		this.jsonApiService.http("markerDetail/pagelist.html", reqdata).subscribe(data => {
			if(this.selectedCarNumber){
				$(".select2-selection__placeholder").text(this.selectedCarNumber);
			}
			if(data.isSuccess){
				var len=data.exhibitDatas.length
				for(var i=0;i<len;i++){
					//载重量保留2位小数
					data.exhibitDatas[i].weight=common.twoDecimal(data.exhibitDatas[i].weight);
					//转换时间格式
					data.exhibitDatas[i].stopTime=lostTimeStr(data.exhibitDatas[i].stopTime);
					data.exhibitDatas[i].loadingTime=lostTimeStr(data.exhibitDatas[i].loadingTime);
				}
				this.tableData = data.exhibitDatas;
				this.totalCount = data.recordCount;
			}
		})
	}
	//删除所选时间
	del_date(){
		this.startTime = '';
		this.endTime ='';
		$("#datetimepicker1").val('').change();
		$("#datetimepicker2").val('').change();
		$("#datetimepicker2").datetimepicker("setStartDate", null);
		$("#datetimepicker1").datetimepicker("setEndDate", null);
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.load();
	}
	jumpRailManage(row){
		localStorage.setItem('storageRailName',row.name);
		this.router.navigate(['/data-statistics/rail/rail-manage'])
	}
	//公司选中回调
	companySelected(data){
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
		this.deviceId = data.deviceId;
		this.carNumber = data.carNumber;
	}
}
